/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.metadata.common.util;

import com.inspur.edp.lcm.metadata.common.Utils;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptUtil {
    final static BASE64Decoder DECODER = new BASE64Decoder();
    final static BASE64Encoder ENCODER = new BASE64Encoder();

    public static String decryptInBASE64(String decryptString) {
        try {
            return new String(DECODER.decodeBuffer(decryptString), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("配置解密失败, 请重新配置或者联系系统管理员。", e);
        }
    }

    public static String encryptInBASE64(String encodeString) {
        if (Utils.isNullOrEmpty(encodeString)) {
            return "";
        }
        try {
            return ENCODER.encode(encodeString.getBytes(StandardCharsets.UTF_8.name()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String encryptInAscii(String text, int offset) {
        if (Utils.isNullOrEmpty(text)) {
            return "";
        }
        char[] chars = text.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char) (chars[i] + offset);
        }
        return new String(chars);
    }

    public static String decryptInAscii(String text, int offset) {
        if (Utils.isNullOrEmpty(text)) {
            return "";
        }
        char[] chars = text.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char) (chars[i] - offset);
        }
        return new String(chars);
    }
}
